
package gui.std;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.Date;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import util.Constants;
import app.Client;
import app.Request;

@SuppressWarnings("serial")
public class GChatPanel extends JPanel {
	
	public GChatPanel(Client c) {
		client = c;
		initialize();
	}
	
	public synchronized void append(String i) {
		log.append(i);
	}
	
	public void showLog() {
		try {
			log.append("Chat Logged in at "+(Date)client.chatReceive()+".\n");
		} 
		catch (Exception e) {e.printStackTrace();}
	}
	
	public void setUpdateAction(Thread t) {
		upt = t;
	}
	
	public void startUpdating() {
		upt.start();
	}
	
	private void initialize() {
		setLayout(new BorderLayout(1, 1));
		
		log = new JTextArea();
		bot = new JPanel(new BorderLayout());
		writer = new JTextArea();
		send = new JButton("", new ImageIcon("./src/gui/std/icons/send_icon.png"));
		
		send.setFocusable(false);
		log.setBackground(Constants.DEFAULT_BACKGROUND_ITEM_COLOR);
		log.setEditable(false);
		log.setFont(Constants.DEFAULT_FONT);
		writer.setBackground(Constants.DEFAULT_BACKGROUND_ITEM_COLOR);
		writer.setFont(Constants.DEFAULT_FONT);
		
		log.setLineWrap(true);
		writer.setLineWrap(true);
		
		send.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (!writer.getText().trim().isEmpty()) {
					log.append(" <Me>: "+writer.getText());
					try {
						Request r = new Request();
						r.setMsg(" <"+client.getUser().getNick()+">: "+ writer.getText());
						client.chatSend(r);
					} 
					catch (IOException e1) {e1.printStackTrace();}
					writer.setText("");
				}
			}
		});
		
		writer.addKeyListener(new KeyAdapter() {
			public void keyTyped(KeyEvent e) {
				super.keyTyped(e);
				if (e.getKeyChar() == '\n')
					send.doClick();
			}
		});
		
		bot.add(new JScrollPane(writer));
		bot.add(send, BorderLayout.EAST);
		
		add(new JScrollPane(log));
		add(bot, BorderLayout.SOUTH);
	}
	
	
	private Client client;
	
	private JPanel bot;
	private JButton send;
	private JTextArea writer;
	private JTextArea log;
	private Thread upt;
}
